
package model;

import java.util.Observable;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * SystemTimer notifies CPU after a random interval of time.
 * @author Sydney Lin
 * @version 1.0 
 */
public class SystemTimer extends Observable implements Runnable
{
  /**
   * Is this thread done yet?
   */
  private boolean my_is_done;
  
  /**
   * Can start count down?
   */
  private boolean my_count_down;
  
  /**
   * The time for each process to run before asked to give up the CPU.
   */
  private int my_time_interval;

  /**
   * Construct a SystemTimer.
   */
  public SystemTimer()
  {
    super();
    my_time_interval = 50;
    my_is_done = false;
    my_count_down = true;
  }

  /**
   * Set whether this thread is done or not.
   * @param the_boolean The boolean.
   */
  public void setIsDone(final boolean the_boolean)
  {
    my_is_done = the_boolean;
  }
  
  /**
   * Set whether this timer can start to count down.
   * @param the_boolean The boolean.
   */
  public void setCountDown(final boolean the_boolean)
  {
    my_count_down = the_boolean;
  }
  
  /**
   * this run is to run as a SystemTimer thread.
   */
  @Override
  public void run()
  {
    while (!my_is_done)
    {
      while (my_count_down)
      {
        final Timer the_timer = new Timer();
        the_timer.schedule(new RemindTask(the_timer), my_time_interval);
      }
    }
  }

  /**
   * RemindTast is the task triggered by timer.
   * 
   */
  class RemindTask extends TimerTask
  {
    Timer t;
    RemindTask(Timer new_t) {
      this.t = new_t;
    }
    /**
     * This run() is to the task to run after certain time.
     */
    public void run()
    {
      my_count_down = false;
      setChanged();
      notifyObservers();
      //System.out.println("Timer interrupt!");
      t.cancel();
    }
  }
}
